import React, { useCallback, PropsWithChildren } from "react";
import { createStyles } from "antd-style";
import { type ModalProps } from "antd";

import { withModal, mountModal, type WrappedComponentProps } from "@yaf/pro-ui";

export type { WrappedComponentProps }

interface NModalProps<T> {
  className?: string,
  style?: React.CSSProperties,
  Content: React.FC<T>,
  contentProps?: T,
  modalProps?: ModalProps,
  modalPadding?: string,
  modalCloseIconTop?: number,
  modalCloseIconRight?: number,
}

export const NModal = function <T>({ className = "", style, Content, contentProps, modalProps, modalPadding = "20px 24px", modalCloseIconRight = 12, modalCloseIconTop = 12, children }: PropsWithChildren<NModalProps<T>>) {
  const { styles } = useStyle({ modalPadding, modalCloseIconRight, modalCloseIconTop });
  const { styles: modalStyles, ...restModalProps } = modalProps ?? {};

  const handleClick = useCallback(() => {
    const ContentModal = withModal(Content);
    mountModal(<ContentModal
      {...contentProps}
      modalProps={{
        className: styles.modal,
        styles: {
          ...modalStyles,
        },
        ...restModalProps,
      }}
    />)
  }, [styles, modalStyles, restModalProps, Content, contentProps, modalProps])

  if (!children) return null;

  return <div className={className} style={style} onClick={handleClick}>{children}</div>
}


const useStyle = createStyles(({ css }, { modalPadding, modalCloseIconTop, modalCloseIconRight }: { 
  modalPadding: string,
  modalCloseIconTop?: number,
  modalCloseIconRight?: number, 
}) => ({
  modal: css`
    .ant-modal-content{
      overflow: hidden;
      padding: ${modalPadding};
      & > .ant-modal-close{
        top: ${modalCloseIconTop}px;
        right: ${modalCloseIconRight}px;
      }
    }
  `
}))




